<template>
  <view class="forum-container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-input">
        <text class="iconfont icon-search"></text>
        <input type="text" v-model="searchKeyword" placeholder="搜索帖子" @confirm="handleSearch" />
      </view>
    </view>
    
    <!-- 帖子列表 -->
    <scroll-view scroll-y class="post-list" @scrolltolower="loadMore" refresher-enabled
      :refresher-triggered="isRefreshing" @refresherrefresh="onRefresh">
      <view class="post-item" v-for="post in posts" :key="post._id" @tap="goToDetail(post._id)">
        <view class="post-header">
          <image class="avatar default-avatar" :src="post.userAvatar" mode="aspectFill" @error="handleImageError"></image>
          <view class="post-info">
            <text class="username">{{ post.userName }}</text>
            <text class="time">{{ formatTime(post.createTime) }}</text>
          </view>
        </view>
        <view class="post-content">
          <text class="title">{{ post.title }}</text>
          <text class="content">{{ post.content }}</text>
          <view class="image-list" v-if="post.images && post.images.length">
            <image v-for="(img, index) in post.images" :key="index" :src="img" mode="aspectFill"
              class="default-image" @error="handleImageError" @tap.stop="previewImage(post.images, index)"></image>
          </view>
        </view>
        <view class="post-footer">
          <view class="action-item">
            <text class="iconfont icon-like"></text>
            <text class="count">{{ post.likeCount || 0 }}</text>
          </view>
          <view class="action-item">
            <text class="iconfont icon-comment"></text>
            <text class="count">{{ post.commentCount || 0 }}</text>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view class="loading" v-if="isLoading">
        <text>加载中...</text>
      </view>
      <view class="no-more" v-if="!hasMore && posts.length > 0">
        <text>没有更多了</text>
      </view>
      <view class="empty" v-if="!isLoading && posts.length === 0">
        <view class="empty-image"></view>
        <text>暂无帖子</text>
      </view>
    </scroll-view>
    
    <!-- 发帖按钮 -->
    <view class="post-btn" @tap="goToPost">
      <text class="iconfont icon-edit"></text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      posts: [],
      searchKeyword: '',
      page: 1,
      pageSize: 10,
      hasMore: true,
      isLoading: false,
      isRefreshing: false,
      total: 0
    }
  },
  onLoad() {
    this.loadPosts()
  },
  methods: {
    // 加载帖子列表
    async loadPosts(isRefresh = false) {
      if (this.isLoading) return
      
      try {
        this.isLoading = true
        if (isRefresh) {
          this.page = 1
          this.hasMore = true
        }
        
        const res = await uniCloud.callFunction({
          name: 'getPosts',
          data: {
            page: this.page,
            pageSize: this.pageSize,
            keyword: this.searchKeyword
          }
        })
        
        if (res.result.code === 0) {
          const newPosts = res.result.data
          if (isRefresh) {
            this.posts = newPosts
          } else {
            this.posts = [...this.posts, ...newPosts]
          }
          this.total = res.result.total
          this.hasMore = res.result.hasMore
          this.page++
        } else {
          uni.showToast({
            title: res.result.msg,
            icon: 'none'
          })
        }
      } catch (error) {
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
        this.isRefreshing = false
      }
    },
    
    // 加载更多
    loadMore() {
      if (this.hasMore && !this.isLoading) {
        this.loadPosts()
      }
    },
    
    // 下拉刷新
    onRefresh() {
      this.isRefreshing = true
      this.loadPosts(true)
    },
    
    // 搜索
    handleSearch() {
      this.loadPosts(true)
    },
    
    // 跳转到帖子详情
    goToDetail(id) {
      uni.navigateTo({
        url: `/pages/forum/detail?id=${id}`
      })
    },
    
    // 跳转到发帖页面
    goToPost() {
      const userInfo = uni.getStorageSync('userInfo')
      if (!userInfo) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        }, 1500)
        return
      }
      uni.navigateTo({
        url: '/pages/forum/post'
      })
    },
    
    // 预览图片
    previewImage(images, current) {
      uni.previewImage({
        urls: images,
        current: images[current]
      })
    },
    
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      // 小于1分钟
      if (diff < 60000) {
        return '刚刚'
      }
      // 小于1小时
      if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前'
      }
      // 小于24小时
      if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前'
      }
      // 小于30天
      if (diff < 2592000000) {
        return Math.floor(diff / 86400000) + '天前'
      }
      
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },
    
    // 处理图片加载错误
    handleImageError(event) {
      const target = event.target
      if (target.classList.contains('avatar')) {
        target.classList.add('default-avatar')
      } else if (target.classList.contains('image-list')) {
        target.classList.add('default-image')
      }
    }
  }
}
</script>

<style>
/* 引入图标字体 */
@font-face {
	font-family: "iconfont";
	src: url('data:font/woff2;charset=utf-8;base64,d09GMgABAAAAAA...') format('woff2');
}

.iconfont {
	font-family: "iconfont" !important;
	font-size: 32rpx;
	font-style: normal;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}

.icon-search:before {
	content: "\e8ef";
}

.icon-like:before {
	content: "\e8c3";
}

.icon-comment:before {
	content: "\e8e8";
}

.icon-edit:before {
	content: "\e8ac";
}

/* 添加默认图片样式 */
.default-avatar {
	background-color: #e0e0e0;
	display: flex;
	align-items: center;
	justify-content: center;
}

.default-avatar::after {

	font-size: 24rpx;
	color: #999;
}

.default-image {
	background-color: #f5f5f5;
	display: flex;
	align-items: center;
	justify-content: center;
}

.default-image::after {

	font-size: 24rpx;
	color: #999;
}

.empty-image {
	background-color: #f5f5f5;
	display: flex;
	align-items: center;
	justify-content: center;
}

.empty-image::after {
	content: "暂无数据";
	font-size: 28rpx;
	color: #999;
}

.forum-container {
  min-height: 100vh;
  background-color: #f8f9fc;
  padding-bottom: 120rpx;
}

.search-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.search-input {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 32rpx;
  padding: 0 20rpx;
  height: 64rpx;
}

.search-input .iconfont {
  font-size: 32rpx;
  color: #999;
  margin-right: 10rpx;
}

.search-input input {
  flex: 1;
  height: 100%;
  font-size: 28rpx;
}

.post-list {
  margin-top: 104rpx;
  height: calc(100vh - 104rpx);
}

.post-item {
  background-color: #fff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.post-info {
  flex: 1;
}

.username {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.time {
  font-size: 24rpx;
  color: #999;
  margin-top: 4rpx;
}

.post-content {
  margin-bottom: 20rpx;
}

.title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
  margin-bottom: 20rpx;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

.image-list image {
  width: calc(33.33% - 20rpx);
  height: 200rpx;
  margin: 10rpx;
  border-radius: 8rpx;
}

.post-footer {
  display: flex;
  align-items: center;
}

.action-item {
  display: flex;
  align-items: center;
  margin-right: 40rpx;
}

.action-item .iconfont {
  font-size: 32rpx;
  color: #999;
  margin-right: 8rpx;
}

.action-item .count {
  font-size: 24rpx;
  color: #999;
}

.loading, .no-more, .empty {
  text-align: center;
  padding: 30rpx;
  color: #999;
  font-size: 28rpx;
}

.empty image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.post-btn {
  position: fixed;
  right: 40rpx;
  bottom: 40rpx;
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #4a6ee0, #3a5bc7);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 16rpx rgba(74, 110, 224, 0.3);
  transition: all 0.3s;
}

.post-btn:active {
  transform: scale(0.9);
}

.post-btn .iconfont {
  font-size: 48rpx;
  color: #fff;
}
</style>